/*
 * @Author: 张笑天
 * @Date: 2018-03-07 17:11:16
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-07-03 11:04:19
 */
import { observable, action } from 'mobx';
import { message } from 'antd';
import { WeaLocaleProvider } from 'ecCom';

import { checkKeyinTab } from '../util/index';
import EmailViewStore from './view';
import Api from '../apis/ops';

const getLabel = WeaLocaleProvider.getLabel;
const initState = {
  loading: false,
  userConfig: {},
  sysConfig: {},
  title: getLabel(19816, '收件箱'),
  selectKey: 'inbox',
  tabKey: 'list',
  tabInfo: [
    {
      route: 'inbox',
      tabKey: 'list',
      type: 'list',
      title: getLabel(17065, '邮件列表'),
      mainTitle: getLabel(17065, '邮件列表'),
      editable: false,
      query: {},
      search: '',
    },
  ],
  viewId: '',
  viewIdInTab: '',
  viewStores: {
    init: new EmailViewStore('init'),
  },
  canGoOut: false,
  todoSetVisible: false,
  todoSetIds: [],
  unReadedListVisible: false,
  unReadedListId: 'init',
  // wait async ops ids
  waitFolderAddedToMoveIds: [],
  waitTagAddedToSetIds: [],
  // add new contact
  addContactVisible: false,
  // export
  exportToDocIds: [],
  defaultSecId: '',
  exportToCustomerIds: [],
  // print
  printEmailIds: [],
  // listTitle
  listTitle: {
    inbox: getLabel('19816', '收件箱'),
    sent: getLabel('19558', '已发送'),
    draft: getLabel('2039', '草稿箱'),
    deleted: getLabel('2040', '垃圾箱'),
    doing: getLabel('83090', '待办邮件'),
    star: getLabel('81337', '标星邮件'),
    inner: getLabel('24714', '内部邮件'),
    folder: getLabel('30915', '我的文件夹'),
    tag: getLabel('81349', '我的标签'),
  },
  updradeLoading: true,
  sortParams: {},
};

export default class EmailMainStore {
  @observable listTitle = initState.listTitle;
  @observable hasMenu = initState.hasMenu;
  @observable userConfig = initState.userConfig;
  @observable sysConfig = initState.sysConfig;
  @observable title = initState.title;
  @observable selectKey = initState.selectKey;
  @observable tabKey = initState.tabKey;
  @observable tabInfo = initState.tabInfo;
  @observable viewId = initState.viewId;
  @observable viewIdInTab = initState.viewIdInTab;
  @observable viewStores = initState.viewStores;
  @observable canGoOut = initState.canGoOut;
  @observable todoSetVisible = initState.todoSetVisible;
  @observable todoSetIds = initState.todoSetIds;
  @observable unReadedListVisible = initState.unReadedListVisible;
  @observable unReadedListId = initState.unReadedListId;
  @observable waitFolderAddedToMoveIds = initState.waitFolderAddedToMoveIds;
  @observable waitTagAddedToSetIds = initState.waitTagAddedToSetIds;
  @observable addContactVisible = initState.addContactVisible;
  @observable exportToDocIds = initState.exportToDocIds;
  @observable exportToCustomerIds = initState.exportToCustomerIds;
  @observable printEmailIds = initState.printEmailIds;
  @observable defaultSecId = initState.defaultSecId;
  @observable updradeLoading = initState.updradeLoading;
  @observable listSearch; // list 中doInit方法记录
  @observable onOpenContact; // 打开新建联系人页面

  // 邮件列表排序参数记录
  @observable sortParams = initState.sortParams;

  @action
  setState = (params = {}) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
    return this;
  }

  @action
  clear = () => this.setState(initState)

  @action emailUpgrade = async (params) => {
    this.updradeLoading = true;
    const res = await Api.emailUpgrade(params);
    return res;
  }

  @action
  addTab = (params = {}) => {
    // Check tab added
    let tabKey = checkKeyinTab(this.tabInfo, params.tabKey);
    if (!tabKey) {
      this.tabInfo.push({
        ...params,
        editable: true,
      });
      tabKey = params.tabKey;
    } else if (tabKey === 'list') {
      this.setState({ tabInfo: this.tabInfo.map(t => ({
        ...t,
        ...(tabKey === t.tabKey ? params : {}),
      })) });
    }
    // Change to addTab
    this.tabKey = tabKey;
    this.title = params.mainTitle;
    this.selectKey = params.route;
    return this;
  }

  @action
  delTab = (tabKey, router) => {
    this.tabInfo = this.tabInfo.filter(tab => tab.tabKey !== tabKey);
    // If delete current tab, back to list
    const back = this.tabKey === tabKey;
    if (back && router) {
      const { route, search, mainTitle, type }
        = this.tabInfo.filter(tab => tab.tabKey === 'list')[0];
      const s = type !== 'list' ? search : !search ? '?ontabchange=1'
        : search.indexOf('ontabchange=1') > 0 ? search : `${search}&ontabchange=1`;
      router.push(`main/email/${route}${s}`);
      this.title = mainTitle;
      this.selectKey = route;
    }
    return this;
  }

  @action
  addViewStore = (key, type) => {
    if (!(key in this.viewStores)) {
      this.viewStores = { ...this.viewStores, [key]: new EmailViewStore(key) };
    }
    type === 'inList' && (this.viewId = key);
    type === 'inTab' && (this.viewIdInTab = key);
  }

  @action
  getConfig = async (params) => {
    // this.loading = true;
    const res = await Api.getConfig(params);
    try {
      if (res.status === '1') {
        this.userConfig = res.userConfig;
        this.sysConfig = res.sysConfig;
      } else {
        message.error(res.msg);
      }
    } catch (e) {
      message.error(e);
    }
    // this.loading = false;
    return res;
  }

  @action
  emailOcrInvoice = async (params) => {
    const res = await Api.emailIdentifyInvoice(params);
    try {
      if (res.flag) {
        message.success(getLabel('515693', '发票识别成功'), 4);
      } else {
        message.error('查验失败，发票信息错误', 4);
      }
    } catch (e) {
      message.error(e, 4);
    }
    return res;
  }
}

// tabInfo = [
//   {
//     route: 'inbox',
//     tabKey: 'list',
//     type: 'list',
//     title: '邮件列表',
//     mainTitle: '邮件列表',
//     editable: false,
//     query: {},
//     search: '',
//   },
//   {
//     route: 'new',
//     tabKey: 'new',
//     type: 'new',
//     title: '写信',
//     mainTitle: '写信',
//     editable: true,
//     query: {},
//     search: '',
//   },
//   {
//     route: 'view',
//     tabKey: '14545',
//     type: 'view',
//     title: 'Re: 查看很长邮件名字的标题',
//     mainTitle: '查看邮件',
//     editable: true,
//     query: {},
//     search: '',
//   },
// ];
